package com.example.demo.shiro;
/*
 * @Desc 
 * @author 蔡超
 * @date 2018/9/25 10:57
 */

import com.example.demo.model.BdUserInfo;
import com.example.demo.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

public class MyShiroRealm extends AuthorizingRealm {

    @Autowired
    public UserService userService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        BdUserInfo bdUserInfo = (BdUserInfo) principalCollection.fromRealm(this.getClass().getName()).iterator().next();
        return new SimpleAuthorizationInfo();
    }

    /**
     * 登陆认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = authenticationToken.getPrincipal().toString();
        BdUserInfo bdUserInfo = userService.getUser(username);
        if(bdUserInfo != null){
            String password = bdUserInfo.getUserPwd();
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username,password,getName());
            return authenticationInfo;
        }
        return null;
    }
}
